<template>
  <view class="report-evidence-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <text class="header-title">补充举报证据</text>
        <view class="header-right"></view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 举报原因 -->
      <view class="reason-section">
        <view class="section-title">举报原因</view>
        <view class="reason-display">
          <text class="reason-text">{{ reportData.reasonValue }}</text>
        </view>
      </view>

      <!-- 图片证明 -->
      <view class="evidence-section">
        <view class="section-header">
          <text class="section-title">图片证明</text>
          <text class="photos-count">{{ uploadedPhotos.length }}/6</text>
        </view>
        <view class="section-subtitle">直观的截图是非常有利的举报证据</view>
        
        <!-- 图片展示区域 -->
        <view class="photos-display">
          <!-- 已上传的照片 -->
          <view 
            v-for="(photo, index) in uploadedPhotos" 
            :key="index" 
            class="photo-item"
          >
            <image :src="photo" class="photo-image" mode="aspectFill"></image>
            <view class="delete-btn" @tap="deletePhoto(index)">
              <text class="delete-text">×</text>
            </view>
          </view>
          
          <!-- 文件上传器 -->
          <view v-if="uploadedPhotos.length < 6" class="upload-item">
            <uni-file-picker 
              ref="filePicker"
              :limit="6 - uploadedPhotos.length" 
              title=""
              :image-styles="imageStyles"
              :preview-image="false"
              :del-icon="false"
              @select="handleSelect"
              @delete="handleDelete"
              @progress="handleProgress"
              @success="handleSuccess"
              @fail="handleFail"
              @exceed="handleExceed"
            ></uni-file-picker>
          </view>
        </view>
      </view>

      <!-- 用户协议提示 -->
      <view class="agreement-section">
        <view class="agreement-title">点击提交即表示您愿意遵守《用户守则》及《隐私政策》规定:</view>
        <view class="agreement-list">
          <text class="agreement-item">1. 授权平台对您提交的材料及相关信息记录进行核实</text>
          <text class="agreement-item">2. 您将对举报的真实性负责，虚假举报信息需承担法律责任</text>
          <text class="agreement-item">3. 如有必要，工作人员可能会向您致电沟通取证</text>
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="bottom-actions">
      <view 
        class="submit-btn" 
        @click="submitReport"
      >
        <text class="btn-text">提交</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getReportUploadSignsApi, submitReportApi } from '@/api/position.js';
import { uploadFileH5 } from '@/utils/file.js';

// 页面参数
const jobId = ref('');
const reasonValue = ref('');

// 举报数据
const reportData = ref({});

// 上传相关
const filePicker = ref(null);
const uploadedPhotos = ref([]);
const isSubmitting = ref(false);

// 图片样式配置
const imageStyles = {
  width: 120,
  height: 120
};

// 获取页面参数
const getPageParams = () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};
  
  jobId.value = options.jobId || '';
  reasonValue.value = decodeURIComponent(options.reasonValue || '');
  
  // 从本地存储获取完整的举报数据
  const storedReportData = uni.getStorageSync('reportData');
  if (storedReportData) {
    reportData.value = storedReportData;
  }
  
  console.log('证据页面获取到的数据:', { jobId: jobId.value, reasonValue: reasonValue.value, reportData: reportData.value });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 获取上传签名
const getUploadSigns = async (fileCount) => {
  try {
    const response = await getReportUploadSignsApi(fileCount);
    return response;
  } catch (error) {
    throw new Error('获取签名失败');
  }
};

// 检测是否为H5平台
const isH5Platform = () => {
  return typeof window !== 'undefined' && window.location && window.location.protocol.startsWith('http');
};

// 使用签名上传文件
const uploadFileWithSign = async (filePath, sign) => {
  console.log('上传文件，签名数据:', sign);
  
  const isH5 = isH5Platform();
  
  if (isH5) {
    // H5平台使用专门的上传方法
    try {
      const result = await uploadFileH5(filePath, sign);
      return result;
    } catch (error) {
      console.error('H5上传失败:', error);
      throw error;
    }
  } else {
    // 原生平台使用uni.uploadFile
    return new Promise((resolve, reject) => {
      uni.uploadFile({
        url: sign.url,
        filePath: filePath,
        name: 'file',
        formData: sign.formData,
        success: (res) => {
          if (res.statusCode === 200 || res.statusCode === 204) {
            resolve(sign.accessPath);
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  }
};

// 选择文件事件
const handleSelect = async (e) => {
  console.log('选择文件:', e);
  
  // 检查是否超出限制
  const maxCount = 6 - uploadedPhotos.value.length;
  if (maxCount <= 0) {
    uni.showToast({
      title: "最多只能上传6张图片",
      icon: "none"
    });
    return;
  }
  
  // 获取选择的文件信息
  const selectedFiles = e.tempFiles || [];
  if (selectedFiles.length === 0) return;
  
  try {
    uni.showLoading({ title: "获取上传签名中..." });

    // 获取上传签名
    const uploadSigns = await getUploadSigns(selectedFiles.length);
    console.log("uploadSigns", uploadSigns);
    console.log("selectedFiles", selectedFiles);
    
    if (!uploadSigns || !Array.isArray(uploadSigns) || uploadSigns.length !== selectedFiles.length) {
      console.error('签名验证失败:', {
        uploadSigns,
        uploadSignsLength: uploadSigns?.length,
        selectedFilesLength: selectedFiles.length,
        isArray: Array.isArray(uploadSigns)
      });
      throw new Error('获取上传签名失败或签名数量不匹配');
    }
    
    uni.showLoading({ title: "上传中..." });
    
    // 使用签名进行直传
    const uploadRes = await Promise.all(
      selectedFiles.map(async (file, index) => {
        const sign = uploadSigns[index];
        try {
          const res = await uploadFileWithSign(file.path, sign);
          return res;
        } catch (error) {
          console.error('单个文件上传失败:', error);
          return null;
        }
      })
    );

    const uploadUrls = uploadRes.filter(res => res !== null && res !== undefined);
    const failedUploads = uploadRes.filter(res => res === null || res === undefined);
    
    // 将新上传的照片添加到现有列表中
    if (uploadUrls.length > 0) {
      uploadedPhotos.value.push(...uploadUrls);
    }
    
    uni.hideLoading();
    
    if (uploadUrls.length > 0) {
      if (failedUploads.length > 0) {
        uni.showToast({
          title: `成功上传${uploadUrls.length}张，${failedUploads.length}张失败`,
          icon: "none"
        });
      } else {
        uni.showToast({
          title: `成功上传${uploadUrls.length}张图片`,
          icon: "success"
        });
      }
    } else {
      uni.showToast({
        title: "所有文件上传失败，请重试",
        icon: "none"
      });
    }
    
    // 清空选择的文件
    if (filePicker.value) {
      filePicker.value.clearFiles();
    }
  
  } catch (error) {
    uni.hideLoading();
    console.error('上传失败:', error);
    
    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
    
    // 上传失败时清空选择的文件
    if (filePicker.value) {
      filePicker.value.clearFiles();
    }
  }
};

// 删除照片
const deletePhoto = (index) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这张照片吗？',
    success: (res) => {
      if (res.confirm) {
        uploadedPhotos.value.splice(index, 1);
      }
    }
  });
};

// 提交举报
const submitReport = async () => {
  if (isSubmitting.value) return;
  
  try {
    isSubmitting.value = true;
    uni.showLoading({ title: "提交中..." });
    
    const submitData = {
      jobId: reportData.value.jobId,
      reportReason: reportData.value.reasonValue,
      reportProves: uploadedPhotos.value
    };
    
    console.log('提交举报数据:', submitData);
    
    // 调用提交接口
    const response = await submitReportApi(submitData);
    
    uni.hideLoading();
    
    // 清除本地存储的举报数据
    uni.removeStorageSync('reportData');
    
    uni.showToast({
      title: '举报提交成功',
      icon: 'success',
      duration: 2000,
      success() {
        setTimeout(() => {
          // 返回到职位详情页面
          uni.navigateBack({
            delta: 2
          });
        }, 2000);
      }
    });
    
  } catch (error) {
    uni.hideLoading();
    console.error('提交举报失败:', error);
    uni.showToast({
      title: error.message,
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};

// 文件上传相关事件处理
const handleDelete = (e) => {
  console.log('删除文件:', e);
};

const handleProgress = (e) => {
  console.log('上传进度:', e);
};

const handleSuccess = (e) => {
  console.log('上传成功:', e);
};

const handleFail = (e) => {
  console.log('上传失败:', e);
};

const handleExceed = (e) => {
  uni.showToast({
    title: '最多只能选择6张图片',
    icon: 'none'
  });
};

// 页面加载
onMounted(() => {
  getPageParams();
});
</script>

<style scoped lang="less">
.report-evidence-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 120rpx; /* 为底部按钮留空间 */
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.header-right {
  width: 60rpx;
}

/* 内容区域 */
.content {
  padding: 0;
}

/* 通用section样式 */
.reason-section,
.evidence-section,
.agreement-section {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.section-subtitle {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 20rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 举报原因显示 */
.reason-display {
  background-color: #f5f5f5;
  border-radius: 8rpx;
  padding: 20rpx;
}

.reason-text {
  font-size: 28rpx;
  color: #333;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 图片相关样式 */
.photos-count {
  font-size: 26rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.photos-display {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.photo-item {
  position: relative;
  width: 200rpx;
  height: 200rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #f5f5f5;
  flex-shrink: 0;
}

.photo-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.delete-text {
  color: #fff;
  font-size: 24rpx;
  line-height: 1;
}

.upload-item {
  width: 200rpx;
  height: 200rpx;
  position: relative;
}

.upload-item :deep(.uni-file-picker__container) {
  width: 100%;
  height: 100%;
}

.upload-item :deep(.uni-file-picker__box) {
  width: 100% !important;
  height: 100% !important;
  border: 2rpx dashed #ddd !important;
  border-radius: 8rpx !important;
  background-color: #f8f9fa !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
}

.upload-item :deep(.uni-file-picker__lists) {
  display: none !important;
}

.upload-item :deep(.uni-icons) {
  font-size: 48rpx !important;
  color: #ccc !important;
}

/* 用户协议样式 */
.agreement-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 16rpx;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

.agreement-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.agreement-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 底部提交按钮 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.submit-btn {
  height: 80rpx;
  background-color: #00bdb4;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.submit-btn:active {
  background-color: #009688;
}

.btn-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #fff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}
</style>
